from flask import Flask, render_template
import pymysql
import threading
import time

app = Flask(__name__)


def update_data():
    while True:
        # 在方法内建立数据库连接
        conn = pymysql.connect(
            user='readonly_user',
            password="",
            host='',
            database='',
            port=,
            charset='utf8'
        )
        cursor = conn.cursor()
        cursor.execute('select * from device order by LNO asc')
        rows = cursor.fetchall()
        cursor.close()
        conn.close()  # 关闭连接
        time.sleep(5)


@app.route('/')
def index():
    # 在方法内建立数据库连接
    conn = pymysql.connect(
        user='',
        password="",
        host='',
        database='',
        port=3306,
        charset='utf8'
    )
    cursor = conn.cursor()
    cursor.execute('select * from device order by LNO asc')
    rows = cursor.fetchall()

    # 统计设备状态和控制模式
    status_counts = {
        '在线': 0,
        '离线': 0,
        '自动': 0,
        '手动': 0
    }

    for row in rows:
        if row[6] == 'Online':
            status_counts['在线'] += 1
        elif row[6] == 'Offline':
            status_counts['离线'] += 1
        if row[9] == 'Auto':
            status_counts['自动'] += 1
        elif row[9] == 'Human':
            status_counts['手动'] += 1

    status_data = [status_counts['在线'], status_counts['离线'], status_counts['自动'], status_counts['手动']]

    # 关闭数据库连接
    cursor.close()
    conn.close()

    return render_template('index.html', data=rows, status_data=status_data)


if __name__ == '__main__':
    update_thread = threading.Thread(target=update_data)
    update_thread.daemon = True
    update_thread.start()
    app.run(host='0.0.0.0', port=8001)






